<template>
	<view class="wrap">
		<view class="bill-details-wrap form">
			<view v-if="!isReadonly" style="color: #fc7e0a; text-align: right; font-size: 12px">等待我审核</view>
			<!-- 单据明细 -->
			<ProblemBillDetailsViewer :period="$GC.APPROVE_PERIOD.handle" :billId="model.ProblemId" billType="invoice"
				@detail-loaded="onDetailLoaded('details')" />
		</view>

		<view class="form-wrap" style="margin-top: 20rpx">
			<u-form class="form" :model="model" ref="uForm" labelWidth="100" labelPosition="top">
				<u-form-item borderBottom label="问题处理反馈" prop="ProblemFeedback" required>
					<u--textarea border="none" v-model="model.ProblemFeedback" placeholder="请输入内容"></u--textarea>
				</u-form-item>
				<u-form-item borderBottom label="问题处理照片" prop="ProblemHandlePic" required>
					<u-upload :deletable="false" :previewFullImage="true" :fileList="ProblemHandlePicList" @afterRead="
							(event) => {
								fileAfterRead(event);
							}
						" @delete="
							(event) => {
								fileDelete(event);
							}
						" name="ProblemHandlePic" multiple :maxCount="5"></u-upload>
				</u-form-item>
				<u-form-item borderBottom label="问题处理视频" prop="ProblemHandleVid">
					<u-upload accept="video" :previewFullImage="true" :fileList="ProblemHandleVidList" @afterRead="
							(event) => {
								fileAfterRead(event);
							}
						" @delete="
							(event) => {
								fileDelete(event);
							}
						" name="ProblemHandleVid" multiple :maxCount="1"></u-upload>
					<u-button @click="showVideoPreview = !showVideoPreview" :plain="true" style="width: 100px"
						type="warning" size="mini">预览视频</u-button>
				</u-form-item>
				<u-transition :show="showVideoPreview">
					<video :src="`${$GC.API_FS_IP}/${model.ProblemHandleVid}`"></video>
				</u-transition>
				<!-- <u-form-item borderBottom label="审批批语" prop="ProblemApproveStr" label-position="top">
					<u--textarea
						maxlength="1000"
						autoHeight
						:count="true"
						:disabled="isReadonly"
						v-model="model.ProblemApproveStr"
						border="none"
						placeholder="请输入"
					></u--textarea>
				</u-form-item> -->
			</u-form>
		</view>

		<view class="approve-line" style="margin-bottom: 80rpx">
			<ProblemApproveFlowViewer :billId="model.ProblemId" billType="invoice"
				@detail-loaded="onDetailLoaded('flow')" />
		</view>
		<view class="bottom-fix-wrap" v-if="!isReadonly">
			<u-row gutter="10" justify="space-between">
				<u-col span="6">
					<view class="demo-layout bg-purple">
						<u-button class="btn" type="error" @click="submit('return')">退回</u-button>
					</view>
				</u-col>
				<u-col span="6">
					<view class="demo-layout bg-purple-light">
						<u-button class="btn" type="primary" @click="submit('finished')">处理完成</u-button>
					</view>
				</u-col>
			</u-row>
		</view>
		<u-picker closeOnClickOverlay :show="showPicker" @close="showPicker = false" @cancel="showPicker = false"
			@confirm="pickerConfirmEve" :columns="pickerColumns"></u-picker>
	</view>
</template>
<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();

	innerAudioContext.autoplay = true;
	import {
		BASEDOC
	} from '@/common/const/index';
	import ProblemBillDetailsViewer from '../pub/approve-details.vue';
	import ProblemApproveFlowViewer from '../pub/approve-flow.vue';
	export default {
		name: 'ProblemFilter',
		components: {
			ProblemApproveFlowViewer, //审批明细
			ProblemBillDetailsViewer // 注册明细页面组件
		},
		data() {
			return {
				ProblemHandlePicList: [], //问题处理照片
				ProblemHandleVidList: [], //问题处理视频

				showVideoPreview: false, //是否预览视频

				rules: {
					ProblemFeedback: {
						type: 'string',
						required: true,
						message: '请填写问题处理反馈'
					}
				},

				showPicker: false,
				pickerColumns: [],
				pickerCurrentAttrName: '',

				showStartTimeDateTimePicker: false,
				showEndTimeDateTimePicker: false,
				dateTimePickerCfg: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				// 表单
				model: {
					ProblemId: '',
					ProblemFeedback: '',
					ProblemHandlePic: '',
					ProblemHandleVid: '',
					ProblemProperty: ''
				},
				status: 'add', //表单状态

				officeSelectList: [],
				userSelectList: [],
				current: 0
			};
		},
		computed: {
			/**
			 * 表单是否只读
			 */
			isReadonly() {
				return this.status === this.$GC.STATUS.browse;
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(params) {
			this.status = params.status;
			this.model.ProblemId = params.ProblemId + '';
			return;
		},
		methods: {
			async fileAfterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let attrName = `${event.name}List`;
				let fileListLen = this[attrName].length;

				lists.map((item) => {
					this[attrName].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[attrName][fileListLen];
					this[attrName].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '上传成功',
							url: `${this.$GC.API_FS_IP}/${result}`
						})
					);
					
					// 将文件名放置到form表单，需要传给后端，因为是多文件上传，所以拼接|符号
					if (this.model[event.name]) {
						this.model[event.name] += '|' + result;
					} else {
						this.model[event.name] = result;
					}
					fileListLen++;
				}
			},

			uploadFilePromise(fileUrl) {
				let authorization = uni.getStorageSync(this.$GC.ACCESS_TOKEN_KEY);
				let url = this.$GC.FILE_UPLOAD_URL;
				let header = {
					Authorization: authorization
				};
				let that = this;
				return new Promise((resolve, reject) => {
					let uploadTask = uni.uploadFile({
						url: url,
						filePath: fileUrl,
						name: 'file',
						header: header,
						name: 'UploadFiles',
						formData: {},
						success: (res) => {
							let resStr = res.data;
							let replaceStr =
							'{"error":{"code":500,"message":"Internal Server Error"}}';
							resStr = resStr.replace(replaceStr, '');
							let fileUploadRes = JSON.parse(resStr);

							// 调用上传文件业务接口，保存文件到具体磁盘上
							let fileUploadParam = {
								FileId: '',
								FileFullName: '',
								tempFile: ''
							};

							let tempFiles = fileUploadRes.files;
							tempFiles.map((tempFile) => {
								let paths = tempFile.path.split(':');
								let fileId = paths[1];

								fileUploadParam.FileFullName = fileId + '_' + tempFile.name;
								fileUploadParam.tempFile = tempFile.path;
								fileUploadParam.FileId = fileId;
							});

							//需要再调用一次fileUpload，将gxObject保存至磁盘中
							that.$api
								.fileUpload(fileUploadParam)
								.then((res) => {
									// 这里res的返回值为空
									setTimeout(() => {
										resolve(fileUploadParam.FileFullName);
									}, 1000);
								})
								.catch((error) => {
								});
						}
					});
				});
			},

			fileDelete(event, type) {},
			// 明细组件以及审批组件加载完成
			onDetailLoaded(type) {},
			refInputClick(e) {
				uni.hideKeyboard();
				let refparam = {
					refType: BASEDOC.PSNDOC,
					queryCondition: {
						pk_org: ''
					}
				};
				let that = this;
				uni.navigateTo({
					url: '/pages/common/listref/listref?refparam=' + JSON.stringify(refparam),
					events: {
						refPageCallBack: function(data) {
							that.model[e] = data.refname;
						}
					},
					success: function(res) {}
				});
			},

			pickerConfirmEve(e) {
				let val = e.value[0];
				if (this.pickerCurrentAttrName) {
					this.model[this.pickerCurrentAttrName] = val;
				}
				this.showPicker = false;
			},
			pickerInputEvent(attr_name) {
				uni.hideKeyboard();
				if (attr_name == 'ProblemType') {
					this.pickerColumns = [
						['设备', '品质', '安全', '工艺', '环保', '人事']
					];
				} else if (attr_name == 'ProblemLevel') {
					this.pickerColumns = [
						['一般问题', '关键问题']
					];
				}
				this.pickerCurrentAttrName = attr_name;
				this.showPicker = true;
			},
			navTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			submit(type) {
				let param = this.model;
				
				if (type == 'return') {
					param.ProblemProperty = '问题被处理人退回';
				} else {
					param.ProblemProperty = '问题已被处理';
				}
				// 退回
				if (type == 'return') {
					this.$api
						.handlerProblem(param)
						.then((res) => {
							uni.showModal({
								title: '提示',
								content: res.message,
								showCancel: false,
								success: function() {
									if (res.success) {
										uni.navigateBack();
									}
								}
							});
						})
						.catch((error) => {
							this.$tool.msg('操作失败！');
						});
					return;
				}

				let {
					ProblemFeedback
				} = this.model;
				if (!ProblemFeedback) {
					return this.$tool.msg('请填写问题处理反馈！')
				}
				if (this.ProblemHandlePicList.length == 0) {
					return this.$tool.msg('请上传问题处理照片！')
				}

				this.$refs.uForm
					.validate()
					.then((res) => {
						this.$api
							.handlerProblem(param)
							.then((res) => {
								let msgStr = '';
								if (res.code != 200) {
									let msgArrs = JSON.parse(res.message);
									if (Array.isArray(msgArrs)) {
										msgArrs.map((item) => {
											msgStr += item;
										});
									}
								} else {
									msgStr = res.message;
								}
								uni.showModal({
									title: '提示',
									content: msgStr,
									showCancel: false,
									success: function() {
										if (res.success) {
											// 跳转到待办页
											uni.navigateBack();
										}
									}
								});
							})
							.catch((error) => {
								this.$tool.msg('操作失败！');
							});
					})
					.catch((errors) => {
						uni.$u.toast('表单校验失败！');
					});
			},
			cancel() {
				uni.navigateBack();
			},
			dateTimePickerCallBack(obj, attr_name) {
				if (attr_name == '') return;
				if (obj == '') {
					this.model[attr_name] = '';
				} else {
					let dateVal = obj.year + '-' + obj.month + '-' + obj.day + ' ';
					let timeVal = obj.hour + ':' + obj.minute + ':' + obj.second;
					this.model[attr_name] = dateVal + timeVal;
				}
			}
		}
	};
</script>
<style scoped lang="scss">
	.wrap {
		font-family: $font-pingfang;
	}

	.form-wrap {
		background-color: white;
		font-family: $font-pingfang;
	}

	.wrap {
		padding: 20rpx;
		background-color: $u-bg-color;
	}

	.u-row {
		margin: 10rpx 0;
	}
</style>